1
从直接 API 调用到 LangChain 抽象
AI010Lesson 5
00:00

超越原始请求

刚开始使用大型语言模型(LLMs)时,开发者通常使用直接的 API 调用(如 OpenAI 的 Python 库)来发送提示并接收完成结果。虽然这种做法是可行的,但随着应用规模扩大,这种方法会变得难以管理。

无状态性问题

大型语言模型本质上是 无状态的。每次你发送一条消息,模型就会‘忘记’你是谁以及之前说过什么。每一次交互都是一张白纸。为了维持对话,你必须每次都手动将完整的对话历史传回给模型。

LangChain 的解决方案

LangChain 引入了 ChatOpenAI 模型包装器。这不仅仅是为了封装而封装——它是实现 模块化 的基础。通过抽象模型调用,我们以后可以轻松更换模型、注入记忆机制,并使用模板,而无需重写整个代码库。

海盗情景
想象一封用“海盗式”俚语写的客户邮件。要将其翻译成正式的企业回复,直接的 API 调用需要硬编码指令。而使用 LangChain,我们可以通过抽象将“风格”(海盗风与正式风)和“内容”(邮件本身)分离开来。
main.py
TERMINALbash — 80x24
> Ready. Click "Run" to execute.
>
Question 1
Why do we say LLMs are "stateless"?
They do not have access to the internet.
They cannot generate the same response twice.
They do not inherently remember previous messages in a conversation.
They are only capable of processing text, not data states.
Challenge: Initialize ChatOpenAI
Solve the problem below.
You are building a creative writing assistant and need to initialize your first LangChain model.

Your task is to create a ChatOpenAI instance named my_llm with a temperature of 0.7 to allow for more creative (non-deterministic) responses.
Task
Write the Python code to import and initialize the model.
Solution:
from langchain_openai import ChatOpenAI
my_llm = ChatOpenAI(temperature=0.7)